<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WeChatLoginController extends Controller
{
    /**
     * 小程序登录接口
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {

        /*$usrname = $request->get('username');
        $avatar = $request->get('avatar');*/
        // 从请求中获取小程序前端传来的 code
        $code = $request->input('code');
        /*if (!$usrname || !$avatar) {
            return ResponseHelper::error(message: '缺少用户信息');
        }*/
        if (!$code) {
            return ResponseHelper::error(message: '缺少code');
        }

        // 配置小程序服务
        $app = app('wechat.mini_program');

        try {
            // 开始事务
            DB::beginTransaction();
            // 使用 code 获取 session 和 openid
            $session = $app->auth->session($code);

            if (isset($session['errcode'])) {
                return ResponseHelper::error(message: '微信登录失败');
            }

            $openid = $session['openid'];
            $sessionKey = $session['session_key'];

            // 这里你可以使用 openid 查找或创建用户
            $user = User::firstOrCreate([
                'wx_open_id' => $openid,
                /*'username' => $usrname,
                'avatar' => $avatar,*/
            ]);
            $user->tokens()->where('name', 'wechat-mini-program')->update(['expires_at' => now()]);
            // 为用户生成 API Token
            $token = $user->createToken('wechat-mini-program', expiresAt: now()->addMonth())->plainTextToken;
            // 提交事务
            DB::commit();
            return ResponseHelper::success(data: [
                'token' => 'Bearer ' . $token,
                'session_key' => $sessionKey,
                'user' => $user,
            ]);
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();
            return ResponseHelper::error(message: '登录失败', data: $e->getMessage());
        }
    }
}
